<template>
  <div>

    <!--    搜索框-->
    <el-input v-model="search" class="input-with-select" placeholder="请输入内容" style="float: left;width: 20%"
              @keyup.enter.native="searchClick">
      <el-button slot="append" icon="el-icon-search" @click="searchClick"></el-button>
    </el-input>
    <el-button
      :disabled="debuilds.length === 0"
      icon="el-icon-delete"
      style="float:left;"
      type="danger"
      @click="alldeBuild">
      一键删除
    </el-button>

    <!--    数据表格-->
    <el-table
      v-loading="loading"
      :data="users.records"
      border
      @selection-change="changeBox"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      element-loading-spinner="el-icon-loading"
      element-loading-text="拼命加载中"
      style="width: 100%">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        align="center"
        label="ID"
        prop="userId"
      >
      </el-table-column>
      <el-table-column
        align="center"
        label="用户名"
        prop="username">

      </el-table-column>
      <el-table-column
        align="center"
        label="性别">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.userSex }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="年龄"
        prop="userAge">
      </el-table-column>
      <el-table-column
        align="center"
        label="手机号"
        prop="userPhone">
      </el-table-column>
      <el-table-column
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="addCleandialog">添加用户</el-button>
    <!--      添加页面-->
    <el-dialog
      :visible.sync="addVisible"
      :title="title">
      <el-form :model="user"
               label-position="left"
               :rules="rule"
               ref="userFromRef"
               label-width="auto">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" v-if="title==='添加'" prop="password">
          <el-input type="password" v-model="user.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" v-if="title==='添加'" prop="checkPass">
          <el-input type="password" v-model="user.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="userSex">
          <el-select v-model="user.userSex" placeholder="性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="userAge">
          <el-input v-model="user.userAge" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="userPhone">
          <el-input v-model="user.userPhone"  autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="userRole">
          <el-select v-model="user.userRole" placeholder="角色">
            <el-option label="用户" value="user"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="addVisible = false">取消</el-button>
          <el-button type="primary" @click="addFrom">{{title}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--    分页-->
    <el-pagination
      :page-size="limit"
      :total="total"
      background
      hide-on-single-page
      layout="prev, pager, next"
      @prev-click="prevClick"
      @next-click="nextClick"
      @current-change="handleCurrentChange">
    </el-pagination>
    <!--      成功提示-->
    <el-dialog
      :visible.sync="res"
    >
      <el-result icon="success" subTitle="请根据提示进行操作" title="成功提示">
        <template slot="extra">
          <el-button size="medium" type="primary" @click="res = false">返回</el-button>
        </template>
      </el-result>
    </el-dialog>

  </div>
</template>

<script>

import User from '@/utils/User'

export default {
  name: 'User',
  data () {
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.user.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else if (!this.isCellPhone(value)) {
        // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    return {
      addVisible: false,
      ids: [],
      debuilds: [],
      users: [],
      search: '',
      title: '',
      total: 0,
      loading: true,
      limit: 10,
      user: {
        userId: '',
        username: '',
        password: '',
        userAge: '',
        userPhone: '',
        userSex: '',
        userRole: '',
        checkPass: ''
      },
      rule: {
        userPhone: [
          {
            required: true, // required就是这个框必须填写
            validator: validatePhone, // 规则
            trigger: 'blur' // blur失去焦点，事件何时触发
          }
        ],
        username: [
          { required: true, message: '请输入用户名!', trigger: 'blur' },
          { message: '长度在3到10个字符非数字', trigger: 'blur', pattern: /^\D{3,10}$/ }
        ],
        password: [
          { required: true, message: '请输入密码!', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6到15个字符之间', trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        userSex: [
          { required: true, message: '不能为空!', trigger: 'blur' }
        ],
        userAge: [
          { required: true, message: '不能为空!', trigger: 'blur' },
          { message: '年龄不能超过二位数字', trigger: 'blur', pattern: /^\d{1,2}$/ }
        ],
        userRole: [
          { required: true, message: '不能为空!', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      res: false
    }
  },
  beforeRouteEnter (to, from, next) {
    if (JSON.parse(sessionStorage.getItem('user')).userRole === 'admin') { // 权限控制的具体规则
      next()
    } else {
      alert('没有权限')
    }
  },
  methods: {
    isCellPhone (val) {
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    handleEdit (index, row) {
      Object.assign(this.user, row)
      this.title = '修改'
      this.addVisible = true
    },
    addCleandialog () {
      this.user = {}
      this.title = '添加'
      this.addVisible = true
    },
    addFrom () {
      if (this.title === '添加') {
        this.$refs.userFromRef.validate((valid) => {
          if (valid) {
            User.addUser(this.user).then((res) => {
              if (res.code === 200) {
                this.$message.success(this.title + '成功!')
                this.addVisible = false
                this.res = true
                this.getUsers(this.users.current, this.limit, this.search)
              } else if (res.code === 508) {
                this.$message.warning('用户名已存在!请重新输入!')
              } else {
                this.$message.error('服务器错误!')
                this.addVisible = false
                this.res = true
              }
            })
          }
        })
      } else {
        this.$refs.userFromRef.validate((valid) => {
          if (valid) {
            console.log(this.user)
            User.editUser(this.user).then((res) => {
              if (res.code === 200) {
                this.$message.success(this.title + '成功!')
                this.addVisible = false
                this.res = true
                this.getUsers(this.users.current, this.limit, this.search)
              } else if (res.code === 508) {
                this.$message.warning('用户名已存在!请重新输入!')
              } else {
                this.$message.error('服务器错误!')
                this.addVisible = false
                this.res = true
              }
            })
          }
        })
      }
    },
    alldeBuild () {
      this.ids = []
      this.debuilds.forEach(builde => {
        this.ids.push(builde.userId)
      })
      User.deleteAllUser(this.ids).then(res => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getUsers(this.users.current, this.limit, this.search)
      })
    },
    changeBox (val) {
      this.debuilds = val
    },
    searchClick () {
      this.getUsers(1, this.limit, this.search)
    },
    handleDelete (index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        User.deleteUser(row.userId).then(res => {
          this.getUsers(this.users.current, this.limit, this.search)
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleCurrentChange (page) {
      this.getUsers(page, this.limit, this.search)
    },
    prevClick () {
      this.getUsers(this.builds.current - 1, this.limit, this.search)
    },
    nextClick () {
      this.getUsers(this.builds.current + 1, this.limit, this.search)
    },
    getUsers (page, limit, search) {
      User.getUsers(page, limit, search).then(res => {
        this.users = res.data
        this.total = parseInt(this.users.total)
        this.loading = false
      })
    }
  },
  created () {
    this.getUsers(0, this.limit, this.search)
  }
}
</script>

<style scoped>

</style>
